package com.edt.ichannel.utils;


import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.date.IceDateFormatUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.regex.Pattern;


/**
 * 
* 
*----------Dragon be here!----------/ 
* 　　　┏┓　　　┏┓ 
* 　　┏┛┻━━━┛┻┓ 
* 　　┃　　　　　　　┃ 
* 　　┃　　　━　　　┃ 
* 　　┃　┳┛　┗┳　┃ 
* 　　┃　　　　　　　┃ 
* 　　┃　　　┻　　　┃ 
* 　　┃　　　　　　　┃ 
* 　　┗━┓　　　┏━┛ 
* 　　　　┃　　　┃神兽保佑 
* 　　　　┃　　　┃代码无BUG！ 
* 　　　　┃　　　┗━━━┓ 
* 　　　　┃　　　　　　　┣┓ 
* 　　　　┃　　　　　　　┏┛ 
* 　　　　┗┓┓┏━┳┓┏┛ 
* 　　　　　┃┫┫　┃┫┫ 
* 　　　　　┗┻┛　┗┻┛ 
* ━━━━━━神兽出没━━━━━━
 */
/**
 * 发送post请求工具类
 * 
 * @author sl
 * @date 2017-5-2
 */
public class HttpPostUtil {

	private static final String APPLICATION_JSON = "application/json";
	private static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
	private static final String ACCEPT_ENCODINT_KEY = "Accept-Encoding";

	private static final String APPLICATION_KEY_VALUE = "application/x-www-form-urlencoded";
	private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
	private static final String APPLICATION_SOAP = "application/soap+xml";
	private static final String CONTENT_TYPE_KEY = "Content-Type";
	private static final String CONTENT_TYPE_VALUE = "text/xml;charset=UTF-8";

	private static final String USER_AGENT_KEY = "User-Agent";
	private static final String USER_AGENT_VALUE = "Apache-HttpClient/4.1.1";

	private static final String ACCEPT_KEY = "Accept";
	private static final String ACCEPT_VALUE = "*/*";

	private static final String ACCEPT_LANGUAGE_KEY = "Accept-Language";
	private static final String ACCEPT_LANGUAGE_VALUE = "zh-cn";
	// 默认编码
	private static final String DEFAULT_ENCODING = "UTF-8";



	private static final Pattern STR_CHN = Pattern.compile("[\u4E00-\u9FA5]+");

	private static Logger logger = LogManager.getLogger(HttpPostUtil.class);

	/**
	 * 用post请求url 发送json
	 * 

	 * @return
	 * http://blog.csdn.net/zgf19930504/article/details/50854141
	 */
	public static String doPostJson(String url, String json,String charSet,int timeOut) {
		String result = "";
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient httpClient = httpClientBuilder.build();
		HttpPost httpPost = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom()  
		        .setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut)
		        .setSocketTimeout(timeOut).build();
		httpPost.setConfig(requestConfig);  
		httpPost.addHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_JSON);
		httpPost.addHeader(ACCEPT_KEY,APPLICATION_JSON);
		httpPost.addHeader(ACCEPT_ENCODINT_KEY,"");
		StringEntity se = new StringEntity(json, charSet);
		se.setContentType(CONTENT_TYPE_TEXT_JSON);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
		httpPost.setEntity(se);
		HttpResponse response;
		try {
			response = httpClient.execute(httpPost);
			int statusCods = response.getStatusLine().getStatusCode();
			if (statusCods == 200) {
				HttpEntity httpEntity = response.getEntity();
				BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "utf-8"));
				StringBuilder stringBuffer = new StringBuilder();
				String str = "";
				while ((str = reader.readLine()) != null) {
					stringBuffer.append(str);
				}
				result = stringBuffer.toString();
			} else {
				result = "错误码" + statusCods;
			}
			
			httpPost.abort();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				if(httpClient != null){
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;
	}/**
	 * 用post请求url 发送json

	 * @return
	 * http://blog.csdn.net/zgf19930504/article/details/50854141
	 */
	public static String doPostKeyValue(String url, String params,String charSet) {
		String result = "";
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient httpClient = httpClientBuilder.build();
		HttpPost httpPost = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom()  
		        .setConnectTimeout(10000).setConnectionRequestTimeout(10000)  
		        .setSocketTimeout(10000).build();  
		httpPost.setConfig(requestConfig);  
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_KEY_VALUE);

		StringEntity se = new StringEntity(params, charSet);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_KEY_VALUE));
		httpPost.setEntity(se);
		HttpResponse response;
		try {
			response = httpClient.execute(httpPost);
			int statusCods = response.getStatusLine().getStatusCode();
			if (statusCods == 200) {
				HttpEntity httpEntity = response.getEntity();
				BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "utf-8"));
				StringBuilder stringBuffer = new StringBuilder();
				String str = "";
				while ((str = reader.readLine()) != null) {
					stringBuffer.append(str);
				}
				result = stringBuffer.toString();
			} else {
				result = "错误码" + statusCods;
			}
			
			httpPost.abort();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				if(httpClient != null){
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	public static String doGet(String url, int timeout,String charSet) {


		String result = "";
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient httpClient = httpClientBuilder.build();

		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom()  
		        .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout)
		        .setSocketTimeout(timeout).build();
		httpGet.setConfig(requestConfig); 
		httpGet.addHeader("accept", "*/*");
		httpGet.addHeader("Content-Type", "text/json; charset=utf-8");
		HttpResponse response;
		try {
			response = httpClient.execute(httpGet);
			int statusCods = response.getStatusLine().getStatusCode();
			if (statusCods == 200) {
				HttpEntity httpEntity = response.getEntity();
				BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charSet));
				StringBuilder stringBuffer = new StringBuilder();
				String str = "";
				while ((str = reader.readLine()) != null) {
					stringBuffer.append(str);
				}
				result = stringBuffer.toString();
			} else {
				result = "错误码" + statusCods;
			}
			httpGet.abort();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;

	}

	/**
	 * @param requestSoap ,serviceAddress,apiMethod
	 *                    报文，地址，方法名
	 * Description: 根据请求报文，请求服务地址获取 响应报文
	 **/
	public static String doPostSoap(String requestSoap, String serviceAddress,String apiMethod) {
		String responseSoap = "";
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		CloseableHttpClient httpClient = httpClientBuilder.build();
		HttpPost httpPost = new HttpPost(serviceAddress);
		RequestConfig requestConfig = RequestConfig.custom()  
				.setConnectTimeout(20000).setConnectionRequestTimeout(20000)
				.setSocketTimeout(20000).build();
		httpPost.setConfig(requestConfig);  
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_SOAP);
		httpPost.setHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE);
		httpPost.setHeader(ACCEPT_LANGUAGE_KEY, ACCEPT_LANGUAGE_VALUE);
		httpPost.setHeader(ACCEPT_KEY, ACCEPT_VALUE);
		httpPost.setHeader(USER_AGENT_KEY, USER_AGENT_VALUE);

		HttpResponse response;
		int statusCode = 0;
		try {
			//设置请求参数
			logger.info(wrapSoapTag(requestSoap,apiMethod));
			byte[] bytes = wrapSoapTag(requestSoap,apiMethod).getBytes(DEFAULT_ENCODING);
			ByteArrayEntity byteArrayEntity = new ByteArrayEntity(bytes, 0, bytes.length);
			httpPost.setEntity(byteArrayEntity);
			response = httpClient.execute(httpPost);
			statusCode = response.getStatusLine().getStatusCode();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		
		if (statusCode == 200) {
			try {
				HttpEntity httpEntity = response.getEntity();
				BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "utf-8"));
				StringBuilder stringBuffer = new StringBuilder();
				String str = "";
				while ((str = reader.readLine()) != null) {
					stringBuffer.append(str);
				}
				responseSoap = stringBuffer.toString();
				return removeSoapTag(responseSoap);
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage(), e);
			}finally{
				httpPost.abort();
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			throw new RuntimeException("请求失败：" + statusCode+":接口异常");
		}
	}

	
	/**
	 * 去掉响应 结果中最外层包裹的SOAP 标签
	 * @return 响应结果字符串
	 */
	public static String removeSoapTag(String responseXML){
		if(null == responseXML || "".equals(responseXML)){
			return responseXML;
		}
		//将字符串中的特殊字符做替换
		responseXML = responseXML.replaceAll("&lt;", "<");
		responseXML = responseXML.replaceAll("&gt;", ">");
		String beginTag = "<return>";
		String endTag = "</return>";
		return IceStringUtils.substringBetween(responseXML, beginTag, endTag);
	}







	


	public static String sendGet(String url,String charSet,String resultCharset) throws Exception {
		String result = "";
		BufferedReader in = null;
		try {
			// String urlNameString = url + "?" + param;
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
//			connection.setRequestProperty("connection", "Keep-Alive");
			// connection.setRequestProperty("user-agent",
			// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			connection.setRequestProperty("Content-Type", "text/plain; charset="+charSet);
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(),resultCharset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(),e);
		}finally{
			// 使用finally块来关闭输入流
			
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		

		return result;
	}

	public static String getMessageCode(String fixStr) {
		Date date = new Date();
		String dataStr = IceDateFormatUtils.dateToString(date, "yyyyMMddHHmmss");
		return fixStr + dataStr;
	}


	/**
	 * 	请求XML 包裹SOAP 标签， 每个 webservice 服务的包裹方式不一定一样， 具体包裹方式如何，可以通过SOAPUI 软件进行查看
	 * @param rquestXML	请求XML 片段
	 * @return 	SOAP 标签包裹的XML 片段
	 */
	private static String  wrapSoapTag(String rquestXML, String apiMethod){
		return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.query.linkage.com/\">\n" +
				"   <soapenv:Header/>\n" +
				"   <soapenv:Body>\n" +
				"      <ser:"+apiMethod+">\n" +
				"         <!--Optional:-->\n" +
				"         <arg0>"+rquestXML+"</arg0>\n" +
				"      </ser:"+apiMethod+">\n" +
				"   </soapenv:Body>\n" +
				"</soapenv:Envelope>\n";

	}
	
	

}
